import React from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
    Input,
    Button,
    notification,
    Radio,
    Modal,
    Upload,
    Tooltip,
    Collapse,
    InputNumber,
} from 'antd';
import { uploadFiles, } from '@/services/resource';
import Styles from '../../style.less'
import { baseUrl } from '@/utils/config.js'
import { checkBeforeFileUpload } from '@/utils/utils'

const { Panel } = Collapse;
const FormItem = Form.Item;

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
    },
};


class Edit extends React.Component {
    constructor(argus) {
        super(argus);

        this.state = {
            fileList: [], // 上传文件成员
            participle: 1,//  是否已分词 1已分词0未分词
            loading: false,
        };
    }

    // 是否已分词
    filesType = e => {
        e.preventDefault();
        this.setState({
            participle: e.target.value,
        });
    }
    infoToParent(key) {
        this.props.callBack(key);
    }
    // 提交修改的内容
    handleUserSubmit = e => {
        e.preventDefault();
        const _this = this;
        const { participle, fileList } = this.state;
        const { form, wordvecId, wordvecType } = this.props;
        form.validateFields((err, values) => {
            if (!err) {
                const formData = new FormData();
                if (fileList.length == 0) {
                    _this.props.form.setFields({
                        files: {
                            errors: [new Error('请上传文件!')],
                        },
                    });
                    return;
                }
                fileList.forEach(file => {
                    formData.append('files', file);
                });
                for (let k in values) {
                    formData.append(k, values[k]);
                }
                formData.append('wordvecId', wordvecId);
                formData.append('datasetType', [1, 0][wordvecType]);
                _this.setState({ loading: true, })
                uploadFiles(formData).then(res => {
                    if (res.retCode == '0') {
                        notification['success']({
                            message: '操作成功',
                            key: '词向量',
                            description: `上传成功`,
                        });
                        _this.props.callBack(false);
                    } else { _this.setState({ loading: false, }) }
                })
            }
        });
    };

    render() {
        const { getFieldDecorator } = this.props.form;
        const { participle, loading, fileList, } = this.state;
        const { isShowUploadModel, wordvecId, } = this.props;
        const props = {
            multiple: true,
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: (file, fileLists) => {
                let find = fileList.find(item => item.name === file.name);
                let isAcceptFileType = checkBeforeFileUpload(file, ['txt']);
                if (!isAcceptFileType.tip) {
                    notification['warning']({
                        message: '警告',
                        key: isAcceptFileType.msg,
                        description: isAcceptFileType.msg
                    });
                    return true;
                }
                if (find) {
                    notification['warning']({
                        message: '警告',
                        key: '存在同名文件',
                        description: '存在同名文件'
                    });
                    return true;
                } else {
                    if (fileLists.length > 5 - this.state.fileList.length) {
                        notification['warning']({
                            message: '警告',
                            key: '每次上传文件个数不超过5个',
                            description: '每次上传文件个数不超过5个'
                        });
                        return true;
                    } else {
                        this.setState(state => ({
                            fileList: [...state.fileList, file],
                        }));
                        return false;
                    }
                }
            },
            fileList,
        };


        return (
            <Modal
                title={`上传文件`}
                maskClosable={false}
                visible={isShowUploadModel}
                width={600}
                onCancel={this.infoToParent.bind(this, false)}
                footer={[
                    <Button key="cancel" onClick={this.infoToParent.bind(this, false)}>取消</Button>,
                    <Button key="primary" type='primary' loading={loading} onClick={this.handleUserSubmit}>确定</Button>
                ]}
            >
                <Form className={Styles.configForm}>
                    <Form.Item label="是否已分词" {...formItemLayout} onChange={this.filesType.bind(this)}>
                        {getFieldDecorator('participle', {
                            rules: [{ required: true }],
                            initialValue: 1,
                        })(
                            <Radio.Group>
                                <Radio value={1} role={'已分词'}>是</Radio>
                                <Radio value={0} role={'未分词'}>否</Radio>
                            </Radio.Group>,
                        )}
                    </Form.Item>
                    {Number(participle) ? null :
                        <Form.Item label="分词粒度" {...formItemLayout}>
                            {getFieldDecorator('partLevel', {
                                rules: [{ required: true }],
                                initialValue: 1,
                            })(
                                <Radio.Group>
                                    <Radio value={1}>词级别</Radio>
                                    <Radio value={0}>字级别</Radio>
                                </Radio.Group>,
                            )}
                        </Form.Item>
                    }
                    <Form.Item label='上传文件' style={{ marginBottom: 0 }} {...formItemLayout}>
                        <div className="dropbox">
                            {getFieldDecorator('files', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请上传文件!',
                                    },
                                ],
                            })(
                                <span>
                                    <Upload {...props} accept=".txt">
                                        <Button size='small'>
                                            <UploadOutlined /> 点击上传
                                        </Button>
                                    </Upload>
                                    <span style={{ padding: '6px 4px', backgroundColor: 'rgba(240, 242, 245, 1)' }}>支持扩展名：.txt&nbsp;&nbsp;
                                    <a target='_blank' download={'模板'} className="ant-dropdown-link" type='link' href={`${baseUrl}/templates/${participle == 1 ? 'corpus_segmented' : 'corpus'}`}>下载示例模板</a>
                                    </span>
                                </span>
                            )}
                        </div>
                    </Form.Item>
                </Form>
            </Modal>
        );
    }
}

const UploadFiles = Form.create()(Edit);

export default UploadFiles;